/**
 * 从 html 代码中抽取 css 和 template
 * @param {string} htmlCode
 * @returns
 */
function extractCssAndBodyFromHtml(htmlCode) {
  const cssRegex = /<style(?:\s+type="text\/css")?>([\s\S]+?)<\/style>/g;
  const bodyRegExp = /<body>([\s\S]+?)<\/body>/; // 匹配body标签中的HTML代码

  let cssCode = "";
  let bodyHtml = "";

  let match;
  while ((match = cssRegex.exec(htmlCode)) !== null) {
    cssCode += match[1];
  }

  const bodyMatch = htmlCode.match(bodyRegExp);
  if (bodyMatch) {
    bodyHtml = bodyMatch[1];
  }

  return { css: cssCode, template: bodyHtml };
}

/**
 * 生成script代码
 * @returns {string}
 */
function createScriptCode() {
  return `
      export default {
        onInit() {
          console.log('onInit')
        }
      }
  `;
}

/**
 * 将template、css、script聚合成为蓝河ux代码
 * @param {string} template
 * @param {string} css
 * @param {string} script
 * @returns
 */
function createUxCode(template, css, script) {
  return `
    <template>${template}</template>
    <script>${script}</script>
    <style>${css}</style>
  `;
}

/**
 * 替换标签
 * @param {string} htmlString
 * @param {string} originalTag
 * @param {string} newTag
 * @returns {string}
 */
function replaceTag(htmlString, originalTag, newTag) {
  const pattern = new RegExp(
    `<${originalTag}.*?>(.*?)<\\/${originalTag}>`,
    "gs"
  );
  const newHtmlString = htmlString.replace(
    pattern,
    `<${newTag}>$1</${newTag}>`
  );
  return newHtmlString;
}

const tagMap = {
  h1: "text",
  h2: "text",
  h3: "text",
  h4: "text",
  h5: "text",
  h6: "text",
  p: "text",
  span: "text",
  button: "div",
  header: "div",
  main: "div",
  section: "div",
  footer: "div",
};

/**
 * 通过 html 生成 blueos 代码
 * @param {string} htmlCode
 * @returns
 */
module.exports.convertToBlueOSCodeFromHtml = (htmlCode) => {
  // 抽取 css 和 template
  let { css, template } = extractCssAndBodyFromHtml(htmlCode);
  // html 的标签转换为蓝河组件
  Object.keys(tagMap).forEach((tag) => {
    template = replaceTag(template, tag, tagMap[tag]);
  });
  // 创建 js 代码
  const script = createScriptCode();
  // 将 css、template、js 组装为蓝河代码
  const uxCode = createUxCode(template, css, script);
  return uxCode;
};
